package syncer.client.bitmap;

public class BitMap {

	private byte[] bitmap;
	private int legalBitLen;
	
	public BitMap(int legalBitLen){// number of bytes
		bitmap = new byte[(int)(legalBitLen/8+0.5)];
		this.legalBitLen = legalBitLen;
	}
	
	public BitMap(byte[] bitmap){
		this.bitmap = bitmap.clone();
	}
	
	/***
	 * index from 0
	 * @param index
	 * @return
	 */
	public int getBitOf(int index){
		index += 1;
		byte area = bitmap[index/8];
		return (area>>(8-index%8))&0x0001;
	}
	
	public void setBitTo1(int index){
		index += 1;
		byte area = bitmap[index/8];
		byte mask = (byte) (0x0001<<(8-index%8));//000..1..00
		bitmap[index/8] = (byte) (area | mask);
	}
	
	public void setBitTo0(int index){
		index += 1;
		byte area = bitmap[index/8];
		byte mask = (byte) (~(0x0001<<(8-index%8)));//111..0..11
		bitmap[index/8] = (byte) (area & mask);
	}
	
	public int byteLength(){
		return bitmap.length;
	}
	
	public int legalBitLength(){
		return legalBitLen;
	}
	
	public void insertNewBit(){
		legalBitLen++;
		int newByteLen = (int)(legalBitLen/8+0.5);
		if(newByteLen>bitmap.length){
			byte[] tmp = bitmap;
			bitmap = new byte[newByteLen];
			for(int i=0;i<tmp.length;i++)
				bitmap[i] = tmp[i];
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
